import { defineStore } from "pinia";
import { codeTableData, menuTree } from "../api/module/login";
import {
  getAppId
} from '@/utils/core'


export const useSystemStore = defineStore({
  id: "system",
  state: () => {
    return {
      token: "",
      systemInfo: {},
      timestamp: "",
      routers: <any[]>[],
      menus: <any[]>[],
      codeTableList: new Map(),
      permissions: [],
      routerFrist: {
        path: "/error/404",
      },
      currentPageInfo: {
        id: "",
      },
      tagListInfo: {
        id: "",
        name: "",
      },
      pageSearchInfo: {},
    };
  },
  actions: {
    async loadRouters() {
      const { data, code } = await menuTree({
        appId: getAppId(),
      });
      const menuTreeList: any[] = data.map((item: any) => item);
      let parentRouter: any[] = [];
      let parentMenus: any[] = [];

      ///router 获取子菜单
      function getAllChildrenRouter(arr: any[], list: any[]) {
        let arrChildrenList: any[];
        // 2. 同一parentId下的数据按orderId升序显示
        // 3. 如果末级节点数据 type=1表示菜单，点击需要跳转到页面；
        arr.map((arrItem: any) => {
          arrChildrenList = list
            .map((listItem: any) => {
              if (listItem["parentId"] == arrItem["id"]) {
                return {
                  id: listItem["id"],
                  parentId: listItem["parentId"],
                  path: "/compage/" + listItem["id"],
                  name: "/compage/" + listItem["id"],
                  meta: {
                    title: listItem["name"],
                    pageGroup: listItem["pageGroup"],
                    requireAuth: true,
                    addition: { ...listItem },
                    pageId: listItem["id"],
                  },
                };
              }
            })
            .filter((val) => val != undefined);
          if (arrChildrenList.length > 0) {
            if (arrItem.children != undefined) {
              arrItem.children = [...arrItem.children, ...arrChildrenList];
            } else {
              arrItem.children = arrChildrenList;
            }

            getAllChildrenRouter(
              arrChildrenList.sort((a, b) => a.orderId - b.orderId),
              list,
            );
          }
        });
        return arr;
      }

      // 1. 根据id和parentId 组织上下级关系，parentId=0表示一级菜单
      // 2. 同一parentId下的数据按orderId升序显示
      // 3. 如果末级节点数据 type=1表示菜单，点击需要跳转到页面；
      // 4. 如果一个页面分类下只有type=2（二级页面）和3（公共页面）的数据，则此节点不显示
      // 5. type=1的节点，如果pageGroup=0点击进入具体页面,如果pageGroup=1,点击进入tab页签，调用/init/getNavByPageId (详见4.1接口)方法获取子页面数据，每个页签再加载具体子页面
      // 6. 如果type=4，且无type=1的子节点，则此节点不渲染

      parentRouter = menuTreeList
        .sort((a, b) => a.orderId - b.orderId)
        .map((element: any) => {
          ///一级菜单  parentId=0
          if (element["parentId"] == 0 || element["parentId"] == "0") {
            return {
              id: element["id"],
              path: "/compage/" + element["id"],
              name: "/compage/" + element["id"],
              // component: BaseLayout,
              meta: {
                title: element["name"],
                pageGroup: element["pageGroup"],
                addition: { ...element },
                pageId: element["id"],
              },
              children: [],
              childrenPopup: [],
            };
          }
        })
        .filter((val) => val != undefined);
      if (parentRouter.length > 0) {
        const list = getAllChildrenRouter(
          parentRouter.sort((a, b) => a.orderId - b.orderId),
          menuTreeList,
        );
        this.routerFrist = getJamp(list);
        this.routers = list;
      }

      ///menu 生成菜单子级关系树
      function getAllChildren(arr: any[], list: any[]) {
        let arrChildrenList: any[];
        arr.map((arrItem: any) => {
          arrChildrenList = list
            .map((listItem: any) => {
              ///菜单这里按照id 生成树
              if (listItem["parentId"] == arrItem["menuId"]) {
                return {
                  id: "/compage/" + listItem["id"],
                  menuId: listItem["id"],
                  parentId: listItem["parentId"],
                  icon: "layui-icon-table",
                  type: listItem["type"],
                  title: listItem["name"],
                  childrenList: [],
                };
              }
            })
            .filter((val) => val != undefined);
          if (arrChildrenList.length > 0) {
            if (arrItem.childrenList != undefined) {
              arrItem.children = [...arrItem.childrenList, ...arrChildrenList];
            } else {
              arrItem.children = arrChildrenList;
            }
            getAllChildren(arrChildrenList, list);
          }
        });
        return arr;
      }
      ///menu 筛选符合条件的展示数据
      function filterHasType1Menu(menuTree: any[]): any[] {
        return menuTree.filter((ele) => {
          // 前置判断，当前type为1，但是子菜单全为2|3则当前菜单直接不显示
          if (
            ele["type"] == 1 &&
            ele.children?.every((child) => [2, 3].includes(child.type))
          ) {
            return false;
          }

          if (ele.children && ele.children.length > 0) {
            const newChildren = filterHasType1Menu(ele.children);
            if (newChildren.length > 0) {
              ele.children = newChildren;
            } else delete ele.children;
          }
          // 如果当前元素的类型是1&&子菜单type 不全为2.3则保留它

          if (
            ele["type"] == 1 &&
            !ele.children?.every((child) => [2, 3].includes(child.type))
          ) {
            return true;
          }
          // 如果当前元素有子级，并且其中至少有一个子级的类型是1，则保留它
          else if (
            ele.children &&
            ele.children.some((item: any) => item["type"] === 1)
          ) {
            return true;
          }
          // 如果当前元素的类型是1，则保留它
          else if (
            ele.children &&
            ele.children.some(
              (item: any) =>
                item.children &&
                item.children.some((it: any) => it["type"] === 1),
            )
          ) {
            return true;
          }
          // 其他情况，过滤掉该元素
          else return false;
        });
      }

      parentMenus = menuTreeList
        .map((element: any) => {
          if (element["parentId"] == 0 || element["parentId"] == "0") {
            if (
              element["type"] == 1 ||
              element.childrenList.some((item: any) => {
                item["type"] == 1;
              })
            ) {
              return {
                id: "/compage/" + element["id"],
                menuId: element["id"],
                type: element["type"],
                parentId: "0",
                icon: "layui-icon-table",
                title: element["name"],
                childrenList: [],
              };
            }
          }
        })
        .filter((val) => val != undefined);
      if (parentMenus.length > 0) {
        this.menus = filterHasType1Menu(
          getAllChildren(parentMenus, menuTreeList),
        );
        console.log(this.menus, "当前处理过的菜单信息");
      }

      function getJamp(list: any) {
        if (list[0].children && list[0].children.length > 0) {
          return getJamp(list[0].children);
        } else {
          list[0]["meta"] = {
            ...list[0]["meta"],
            affix: true,
            closable: false,
          };
          return list[0];
        }
      }
    },
    async codeTableInfo() {
      const { data, code } = await codeTableData({
        appId: getAppId(),
      });
      if (code == "1000") {
        // this.codeTableList = data
        this.codeTableList = new Map(
          data.map((item: { codeDataTypeId: any; codeList: any }) => [
            item.codeDataTypeId,
            item.codeList,
          ]),
        );
      }
    },
    removeLoginInfo() {
      this.token = "";
      this.systemInfo = {};
      this.timestamp = "";
      this.routers = <any[]>[];
      this.menus = <any[]>[];
      // this.codeTableList = {}
      // this.codeTableList.clear()
    },
  },
  persist: {
    storage: localStorage,
    paths: [
      "token",
      "systemInfo",
      "timestamp",
      "routers",
      "menus",
      "codeTableList",
    ],
  },
});
